package com.jianying.day08;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: Flink01_KeyedState_ValueState_1
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/9 09:40
 * @Version: 1.0
 */
public class Flink01_KeyedState_ValueState_1 {
    public static void main(String[] args) throws Exception {
        // TODO 检测每种传感器水位值，如果连续的两个水位差值超过10，就输出报警
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888)
                .map(new WaterSensorMapFunction());

        // TODO 按键分组 ID
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(WaterSensor::getId);

        // TODO 分组后数据处理
        // keyByDS.process(
        //         new KeyedProcessFunction<String, WaterSensor, String>() {
        //             // TODO 错误的，成员变量作用范围是整个分区，所有分组共享该变量 ws1 ws2
        //             Integer lastVc = 0;
        //             @Override
        //             public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
        //                 Integer curVc = value.getVc();
        //                 if(Math.abs(curVc - lastVc) > 10) {
        //                     out.collect("传感器:" + ctx.getCurrentKey() + "，当前水位值：" + curVc + ",上一次水位值：" + lastVc + "差大于10");
        //                 }
        //                 lastVc = curVc;
        //             }
        //         }
        // ).print();

        keyByDS.process(
                new KeyedProcessFunction<String, WaterSensor, String>() {
                    // TODO 使用Map实现
                    Map<String, Integer> lastVcMap = new HashMap<>();
                    @Override
                    public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        String id = ctx.getCurrentKey();
                        Integer lastVc = lastVcMap.get(id) == null ? 0 : lastVcMap.get(id);
                        Integer curVc = value.getVc();

                        if(Math.abs(curVc - lastVc) > 10) {
                            out.collect("传感器:" + id + "，当前水位值：" + curVc + ",上一次水位值：" + lastVc + "差大于10");
                        }
                        lastVcMap.put(id, curVc);
                    }
                }
        ).printToErr();

        env.execute();
    }
}
